<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="销售单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入销售单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:item:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:item:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:item:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:item:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="销售单号" align="center" prop="orderId">
        <template slot-scope="scope">
          <span>{{ getOrderNo(scope.row.orderId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="productId">
        <template slot-scope="scope">
          <span>{{ getProductName(scope.row.productId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售数量" align="center" prop="quantity" />
      <el-table-column label="销售单价" align="center" prop="sellingPrice">
        <template slot-scope="scope">
          <span>{{ scope.row.sellingPrice ? '¥' + scope.row.sellingPrice.toLocaleString('zh-CN', {minimumFractionDigits: 2, maximumFractionDigits: 2}) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:item:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:item:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="销售单号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入关联销售单id" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入关联商品id" />
        </el-form-item>
        <el-form-item label="销售数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入销售数量" />
        </el-form-item>
        <el-form-item label="销售单价" prop="sellingPrice">
          <el-input v-model="form.sellingPrice" placeholder="请输入销售单价" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listItem, getItem, delItem, addItem, updateItem } from "@/api/system/item"
import { listOrder } from "@/api/system/order"
import { listProduct } from "@/api/system/product"

export default {
  name: "Item",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售明细表格数据
      itemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        productId: null,
        productName: null,
        orderNo: null
      },
      // 表单参数
      form: {},
      // 订单ID到订单号的映射
      orderNoMap: {},
      // 商品ID到商品名称的映射
      productNameMap: {},
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "关联销售单id不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "关联商品id不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "销售数量不能为空", trigger: "blur" }
        ],
        sellingPrice: [
          { required: true, message: "销售单价不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询销售明细列表 */
    getList() {
      this.loading = true
      // 创建查询参数副本，移除productName和orderNo，避免传递给后端导致类型转换错误
      const queryParamsWithoutStrings = { ...this.queryParams };
      delete queryParamsWithoutStrings.productName;
      delete queryParamsWithoutStrings.orderNo;
      
      listItem(queryParamsWithoutStrings).then(response => {
        let filteredItems = response.rows;
        
        // 获取所有需要的ID
        const allOrderIds = [...new Set(filteredItems.map(item => item.orderId).filter(id => id))];
        const allProductIds = [...new Set(filteredItems.map(item => item.productId).filter(id => id && typeof id === 'number'))];
        
        // 如果有查询条件，在前端进行过滤
        if (this.queryParams.productName || this.queryParams.orderNo) {
          // 并行加载所有可能涉及的数据
          Promise.all([
            this.loadOrderNumbersAsync(allOrderIds),
            this.loadProductNamesAsync(allProductIds)
          ]).then(() => {
            // 根据查询条件过滤结果
            filteredItems = filteredItems.filter(item => {
              // 销售单号过滤
              if (this.queryParams.orderNo) {
                const orderNo = this.getOrderNo(item.orderId);
                if (!orderNo || !orderNo.includes(this.queryParams.orderNo)) {
                  return false;
                }
              }
              
              // 商品名称过滤
              if (this.queryParams.productName) {
                const productName = this.getProductName(item.productId);
                if (!productName || !productName.includes(this.queryParams.productName)) {
                  return false;
                }
              }
              
              return true;
            });
            
            this.itemList = filteredItems;
            this.total = filteredItems.length;
            this.loading = false;
          });
        } else {
          // 常规流程，不需要前端过滤
          this.itemList = filteredItems;
          this.total = response.total;
          
          // 并行加载相关数据
          Promise.all([
            this.loadOrderNumbersAsync(allOrderIds),
            this.loadProductNamesAsync(allProductIds)
          ]).finally(() => {
            this.loading = false;
          });
        }
      })
    },
    
    /** 异步加载销售单号 */
    loadOrderNumbersAsync(orderIds) {
      if (orderIds.length > 0) {
        return listOrder({ ids: orderIds.join(',') }).then(response => {
          // 构建订单ID到订单号的映射
          response.rows.forEach(order => {
            this.$set(this.orderNoMap, order.id, order.orderNo)
          })
        })
      }
      return Promise.resolve()
    },
    
    /** 异步加载商品名称 */
    loadProductNamesAsync(productIds) {
      if (productIds.length > 0) {
        return listProduct({ ids: productIds.join(',') }).then(response => {
          if (response.rows && response.rows.length > 0) {
            // 构建商品ID到商品名称的映射
            response.rows.forEach(product => {
              this.$set(this.productNameMap, product.id, product.name);
            });
          }
          // 对于未找到的商品，使用默认名称
          productIds.forEach(id => {
            if (!this.productNameMap[id]) {
              this.$set(this.productNameMap, id, `未知商品`);
            }
          });
        }).catch(error => {
          console.error('加载商品名称失败:', error);
          // 出错时使用默认名称
          productIds.forEach(id => {
            this.$set(this.productNameMap, id, `未知商品`);
          });
        });
      }
      return Promise.resolve()
    },
    

    
    /** 根据商品ID获取商品名称 */
    getProductName(productId) {
      return this.productNameMap[productId] || `未知商品`;
    },
    
    /** 根据订单ID获取订单号 */
    getOrderNo(orderId) {
      return this.orderNoMap[orderId] || orderId
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        productId: null,
        quantity: null,
        sellingPrice: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加销售明细"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getItem(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改销售明细"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除销售明细编号为"' + ids + '"的数据项？').then(function() {
        return delItem(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/item/export', {
        ...this.queryParams
      }, `item_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
